package com.itheima.controller;

import com.itheima.dto.AddMsg;
import com.itheima.pojo.*;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {

        String name = user.getUserName();
        String userPwd = user.getUserPwd();
        log.info("登录: {},{}", name, userPwd);
        boolean e = userService.login(name, userPwd);

        //登录成功,生成令牌,下发令牌
        if (e == true) {
            return Result.success(userService.getAvatarByName(name));
        }

        //登录失败, 返回错误信息
        return Result.error("用户名或密码错误");
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) throws IOException {

        log.info("注册: {},{}", user.getUserName(), user.getUserPwd());
        boolean e = userService.register(user.getUserName(), user.getUserPwd());
        //登录成功,生成令牌,下发令牌
        if (e == true) {
            return Result.success();
        }
        //登录失败, 返回错误信息
        return Result.error("该用户名已被注册");
    }

    @PostMapping("/updateUserAvatar")
    public Result updateUserAvatar(@RequestBody User user) {
        log.info("更新头像: {},{}", user.getUserName(), user.getUserAvatar());
        userService.updateUserAvatar(user.getUserName(), user.getUserAvatar());
        return Result.success();
    }



    @GetMapping("/getUserDetails")
    public Result getUserDetails(@RequestParam String userName) {
        log.info("获取信息:{}", userName);
        String avatar = userService.getAvatarByName(userName);
        log.info("获取信息:{}", avatar);
        return new Result(1, "success", avatar);
    }

}





